<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 根据附件表的id返回url地址
 * @param  [type] $id [description]
 * @return [type]     [description]
 */
use \think\Session;
use \think\Db;
function geturl($id)
{
	if ($id) {
		$geturl = \think\Db::name("attachment")->where(['id' => $id])->find();
		if($geturl['status'] == 1) {
			//审核通过
			return $geturl['filepath'];
		} elseif($geturl['status'] == 0) {
			//待审核
			return '/uploads/xitong/beiyong1.jpg';
		} else {
			//不通过
			return '/uploads/xitong/beiyong2.jpg';
		} 
    }
    return false;
}


/**
 * [SendMail 邮件发送]
 * @param [type] $address  [description]
 * @param [type] $title    [description]
 * @param [type] $message  [description]
 * @param [type] $from     [description]
 * @param [type] $fromname [description]
 * @param [type] $smtp     [description]
 * @param [type] $username [description]
 * @param [type] $password [description]
 */
function SendMail($address)
{
    vendor('phpmailer.PHPMailerAutoload');
    //vendor('PHPMailer.class#PHPMailer');
    $mail = new \PHPMailer();          
     // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();                
    // 设置邮件的字符编码，若不指定，则为'UTF-8'
    $mail->CharSet='UTF-8';         
    // 添加收件人地址，可以多次使用来添加多个收件人
    $mail->AddAddress($address); 

    $data = \think\Db::name('emailconfig')->where('email','email')->find();
            $title = $data['title'];
            $message = $data['content'];
            $from = $data['from_email'];
            $fromname = $data['from_name'];
            $smtp = $data['smtp'];
            $username = $data['username'];
            $password = $data['password'];   
    // 设置邮件正文
    $mail->Body=$message;           
    // 设置邮件头的From字段。
    $mail->From=$from;  
    // 设置发件人名字
    $mail->FromName=$fromname;  
    // 设置邮件标题
    $mail->Subject=$title;          
    // 设置SMTP服务器。
    $mail->Host=$smtp;
    // 设置为"需要验证" ThinkPHP 的config方法读取配置文件
    $mail->SMTPAuth=true;
    //设置html发送格式
    $mail->isHTML(true);           
    // 设置用户名和密码。
    $mail->Username=$username;
    $mail->Password=$password; 
    // 发送邮件。
    return($mail->Send());
}


/**
 * 阿里大鱼短信发送
 * @param [type] $appkey    [description]
 * @param [type] $secretKey [description]
 * @param [type] $type      [description]
 * @param [type] $name      [description]
 * @param [type] $param     [description]
 * @param [type] $phone     [description]
 * @param [type] $code      [description]
 * @param [type] $data      [description]
 */
function SendSms($param,$phone)
{
    // 配置信息
    import('dayu.top.TopClient');
    import('dayu.top.TopLogger');
    import('dayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
    import('dayu.top.ResultSet');
    import('dayu.top.RequestCheckUtil');

    //获取短信配置
    $data = \think\Db::name('smsconfig')->where('sms','sms')->find();
            $appkey = $data['appkey'];
            $secretkey = $data['secretkey'];
            $type = $data['type'];
            $name = $data['name'];
            $code = $data['code'];
    
    $c = new \TopClient();
    $c ->appkey = $appkey;
    $c ->secretKey = $secretkey;
    
    $req = new \AlibabaAliqinFcSmsNumSendRequest();
    //公共回传参数，在“消息返回”中会透传回该参数。非必须
    $req ->setExtend("");
    //短信类型，传入值请填写normal
    $req ->setSmsType($type);
    //短信签名，传入的短信签名必须是在阿里大于“管理中心-验证码/短信通知/推广短信-配置短信签名”中的可用签名。
    $req ->setSmsFreeSignName($name);
    //短信模板变量，传参规则{"key":"value"}，key的名字须和申请模板中的变量名一致，多个变量之间以逗号隔开。
    $req ->setSmsParam($param);
    //短信接收号码。支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，一次调用最多传入200个号码。
    $req ->setRecNum($phone);
    //短信模板ID，传入的模板必须是在阿里大于“管理中心-短信模板管理”中的可用模板。
    $req ->setSmsTemplateCode($code);
    //发送
    

    $resp = $c ->execute($req);
}


/**
 * 替换手机号码中间四位数字
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function hide_phone($str){
    $resstr = substr_replace($str,'****',3,4);  
    return $resstr;  
}

//随机生成唯一订单号
function order_sn(){
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    return (String) $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') .time(). substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
}

   function build_order_no()
        {
            /* 选择一个随机的方案 */
            mt_srand((double) microtime() * 1000000);
         
            return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        }


     function getcwds($user_id,$money,$order){
        
        $lis = Db::name('relation')->where('game_user_id',$user_id)->value('invitation_code');
        
        $agent = Db::name('ratio')->where('request',$lis)->find();
      
        $li = $agent['charge_ratio'];//比率
        $agent_id = $agent['agent_id'];
        $pid = $agent['pid'];
        //查询账户余额
        $agent_money = Db::name('agent')->where('id',$agent_id)->value('last_money');
        //查询是否有上级
        $agents = Db::name('ratio')->where('agent_id',$pid)->find();
      
        if($agents){
            $lit = $agents['charge_ratio'];//比率
            $agent_ids = $agents['agent_id'];
            $pid = $agents['pid'];
           //查询账户余额
           $agent_moneys = Db::name('agent')->where('id',$agent_ids)->value('last_money');
            $sanji =Db::name('ratio')->where('agent_id',$pid)->find();
            if($sanji){
                    $lits = $sanji['charge_ratio'];//比率
                    $agents = $sanji['agent_id'];
                     //查询账户余额
                     $agent_mon = Db::name('agent')->where('id',$agents)->value('last_money');
                    $yongq = $money*$lits*0.01*(1-$lit*0.01);
                    $yongs = $money*$lits*0.01*$lit*0.01*(1-$li*0.01);
                    $yonga = $money*$lits*0.01*$lit*0.01*$li*0.01;

            }
            if($agent && $agents && !$sanji){
                $yong = $money*$lit*0.01*(1-$li*0.01);
                $yongs = $money*$lit*0.01*$li*0.01;

                $dat['agent_id']=$agent_id;
                $dat['recharge_money']=$money;
                $dat['order_num'] = $order;
                $dat['charge_ratio']=$li;
                $dat['charge_money']=$yongs;
                 $dat['last_money']=$agent_money;
                 $dat['add_time']=time();

                $da['agent_id']=$agent_ids;
                $da['recharge_money']=$money;
                $da['order_num'] = $order;
                $da['charge_ratio']=$lit;
                $da['charge_money']=$yong;
                $da['last_money']=$agent_moneys;
                $da['add_time']=time();
                $res = Db::name('charge')->insert($dat);
                $rea = Db::name('charge')->insert($da);
                 if($res && $rea){
                    Db::name('agent')->where('id',$agent_id)->setInc('last_money',$yongs);
                    Db::name('agent')->where('id',$agent_ids)->setInc('last_money',$yong);
                }

            }

            if($agent && $agents && $sanji){

                $dat['agent_id']=$agent_id;
                $dat['add_time']=time();
                $dat['recharge_money']=$money;
                $dat['order_num'] = $order;
                $dat['charge_ratio']=$li;
                $dat['charge_money']=$yonga;
                 $dat['last_money']=$agent_money;
                $da['agent_id']=$agent_ids;
            
                $da['recharge_money']=$money;
                $da['order_num'] = $order;
                $da['charge_ratio']=$lit;
                $da['charge_money']=$yongs;
                 $da['last_money']=$agent_moneys;
                $da['add_time']=time();

                $das['agent_id']=$agents;
                $das['recharge_money']=$money;
                $das['order_num'] = $order;
                $das['charge_ratio']=$lits;
                $das['charge_money']=$yongq;
                 $das['last_money']=$agent_mon;
                 $das['add_time']=time();

                $rey = Db::name('charge')->insert($dat);
                $rea = Db::name('charge')->insert($da);
                $ress = Db::name('charge')->insert($das);
                  if($ress && $rea && $rey){
                    Db::name('agent')->where('id',$agent_id)->setInc('last_money',$yonga);
                    Db::name('agent')->where('id',$agent_ids)->setInc('last_money',$yongs);
                    Db::name('agent')->where('id',$agents)->setInc('last_money',$yongq);
                }
            }


        }else{
            
               $re = $money*$li*0.01;
                $das['agent_id']=$agent_id;
                $das['recharge_money']=$money;
                $das['order_num'] = $order;
                $das['charge_ratio']=$li;
                $das['charge_money']=$re;
                 $das['add_time']=time();
                $das['last_money']=$agent_money;
                
                $res = Db::name('charge')->insert($das);
                if($res){
                    Db::name('agent')->where('id',$agent_id)->setInc('last_money',$re);
                }

        }
    
    }
function https_request($url, $data = null,$time_out=60,$out_level="s",$headers=array())
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    if($out_level=="s")
    {
        //超时以秒设置
        curl_setopt($curl, CURLOPT_TIMEOUT,$time_out);//设置超时时间
    }elseif ($out_level=="ms") 
    {
        curl_setopt($curl, CURLOPT_TIMEOUT_MS,$time_out);  //超时毫秒，curl 7.16.2中被加入。从PHP 5.2.3起可使用 
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    if($headers)
    {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//如果有header头 就发送header头信息
    }
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

function get_client_ip() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    }
    return $ip;
}

/**
     * 发送post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }

 function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
         curl_setopt($ch,CURLOPT_HEADER,0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    

function random(){
        $arr=array();
        $count1=0;
        $count = 0;
        $return = array();
        while ($count < 6) 
         {
         $return[] = mt_rand(0, 9);
         $return = array_flip(array_flip($return));
         $count = count($return);
         } //www.jb51.net
         $data = "";
        foreach($return as $value)
         {
          $data = $value;
         }
         return $data;

  }
 
 function numbercount($agent_id){
     //查询房卡已售总数
     $count = Db::name('order')->where('agent_id',$agent_id)->sum('qili_gold');
     return $count;
 }
  function numbermonth($agent_id){
     //近一个月房卡总数
    $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));//当月第一天
        $tomar=date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));//当月最后一天
        $BeginDates = strtotime($BeginDate);
        $tomars = strtotime($tomar);
        $wheres['add_time'] = [['>=',$BeginDates],['<=',$tomars]];
        $month = Db::name('order')->where($wheres)->where('agent_id',30)->sum('qili_gold');
    
       return $month;
 }
  function numberday($agent_id){
     //当天房卡数
    $daybegin=strtotime(date("Ymd"));
    $dayend=$daybegin+86400;
    $wherea['add_time'] = [['>=',$daybegin],['<=',$dayend]];
    $day = Db::name('order')->where($wherea)->where('agent_id',$agent_id)->sum('qili_gold');
    return $day;
 }
  function nums($agent_id){
     //总代理下子集总交易量
         $list = Db::name('ratio')->where('agent_id',$agent_id)->select();
         $res = Db::name('ratio')->where('pid',$agent_id)->select();//查询所有二级代理商
         $lis = [];
         foreach ($res as $k => $v) {
           //定义一个空数组为二级分类的名字
           $res[$k]['child'] = [];
           //查询二级分类。条件为父id等于等级分类的id
          $lis = Db::name('ratio')->where('pid',$v['agent_id'])->select();
               }
         $agent=array_merge($res,$lis);//合并数组
         $agents=array_merge($agent,$list);//合并数组

          $num = 0;
           foreach ($agents as $key => $value) {
               $agent_id = $value['agent_id'];
                $nums = Db::name('order')->where('agent_id',$agent_id)->sum('recharge_money');
                 $num += $nums;
                   
                }
                return $num;
          }